Down with .as_slice()!
authorAlex Crichton <alex@alexcrichton.com>
Fri, 6 Feb 2015 08:06:39 +0000 (00:06 -0800)
committerAlex Crichton <alex@alexcrichton.com>
Fri, 6 Feb 2015 23:10:05 +0000 (15:10 -0800)
48 files changed:
src/bin/bench.rs
src/bin/build.rs
src/bin/cargo.rs
src/bin/doc.rs
src/bin/git_checkout.rs
src/bin/login.rs
src/bin/new.rs
src/bin/read_manifest.rs
src/bin/run.rs
src/bin/search.rs
src/bin/test.rs
src/cargo/core/dependency.rs
src/cargo/core/manifest.rs
src/cargo/core/package.rs
src/cargo/core/package_id.rs
src/cargo/core/package_id_spec.rs
src/cargo/core/resolver/encode.rs
src/cargo/core/resolver/mod.rs
src/cargo/core/shell.rs
src/cargo/core/source.rs
src/cargo/core/summary.rs
src/cargo/lib.rs
src/cargo/ops/cargo_clean.rs
src/cargo/ops/cargo_compile.rs
src/cargo/ops/cargo_new.rs
src/cargo/ops/cargo_package.rs
src/cargo/ops/cargo_read_manifest.rs
src/cargo/ops/cargo_run.rs
src/cargo/ops/cargo_rustc/compilation.rs
src/cargo/ops/cargo_rustc/context.rs
src/cargo/ops/cargo_rustc/custom_build.rs
src/cargo/ops/cargo_rustc/engine.rs
src/cargo/ops/cargo_rustc/fingerprint.rs
src/cargo/ops/cargo_rustc/mod.rs
src/cargo/ops/cargo_test.rs
src/cargo/ops/lockfile.rs
src/cargo/ops/registry.rs
src/cargo/sources/git/source.rs
src/cargo/sources/git/utils.rs
src/cargo/sources/path.rs
src/cargo/sources/registry.rs
src/cargo/util/config.rs
src/cargo/util/errors.rs
src/cargo/util/process_builder.rs
src/cargo/util/profile.rs
src/cargo/util/to_semver.rs
src/cargo/util/toml.rs
src/registry/lib.rs

index 99fa48eb06a8ebec753b1ffa0b34e6c84da96f3f..8db4aa930f6b33131c7fbb6a53a0353e017d4158 100644 (file)
@@ -61,7 +61,7 @@ pub fn execute(options: Options, config: &Config) -> CliResult<Option<()>> {
             jobs: options.flag_jobs,
             target: options.flag_target.as_ref().map(|s| s.as_slice()),
             dev_deps: true,
-            features: options.flag_features.as_slice(),
+            features: &options.flag_features,
             no_default_features: options.flag_no_default_features,
             spec: options.flag_package.as_ref().map(|s| s.as_slice()),
             lib_only: false,
@@ -70,7 +70,7 @@ pub fn execute(options: Options, config: &Config) -> CliResult<Option<()>> {
     };
 
     let err = try!(ops::run_benches(&root, &ops,
-                                    options.arg_args.as_slice()).map_err(|err| {
+                                    &options.arg_args).map_err(|err| {
         CliError::from_boxed(err, 101)
     }));
     match err {
index 96a6be5b55c3fe28cf5d7f5fdb9cb4b8bd52bb8a..a617f6459abd98ba49d32d81b2700a331640e06d 100644 (file)
@@ -64,7 +64,7 @@ pub fn execute(options: Options, config: &Config) -> CliResult<Option<()>> {
         jobs: options.flag_jobs,
         target: options.flag_target.as_ref().map(|t| t.as_slice()),
         dev_deps: false,
-        features: options.flag_features.as_slice(),
+        features: &options.flag_features,
         no_default_features: options.flag_no_default_features,
         spec: options.flag_package.as_ref().map(|s| s.as_slice()),
         lib_only: options.flag_lib,
index 95ebc1c2bbd5dcd97f36b4348f46640974217498..cdaa43adfe39d2d93284463654747b3518a21047 100644 (file)
@@ -96,7 +96,7 @@ fn execute(flags: Flags, config: &Config) -> CliResult<Option<()>> {
         return Ok(None)
     }
 
-    let (mut args, command) = match flags.arg_command.as_slice() {
+    let (mut args, command) = match &flags.arg_command[] {
         "" | "help" if flags.arg_args.len() == 0 => {
             config.shell().set_verbose(true);
             let args = &["foo".to_string(), "-h".to_string()];
@@ -105,22 +105,22 @@ fn execute(flags: Flags, config: &Config) -> CliResult<Option<()>> {
             cargo::process_executed(r, &mut **config.shell());
             return Ok(None)
         }
-        "help" if flags.arg_args[0].as_slice() == "-h" ||
-                  flags.arg_args[0].as_slice() == "--help" =>
+        "help" if flags.arg_args[0] == "-h" ||
+                  flags.arg_args[0] == "--help" =>
             (flags.arg_args, "help"),
-        "help" => (vec!["-h".to_string()], flags.arg_args[0].as_slice()),
+        "help" => (vec!["-h".to_string()], &flags.arg_args[0][]),
         s => (flags.arg_args.clone(), s),
     };
     args.insert(0, command.to_string());
     args.insert(0, "foo".to_string());
 
     macro_rules! cmd{ ($name:ident) => (
-        if command.as_slice() == stringify!($name).replace("_", "-").as_slice() {
+        if command == stringify!($name).replace("_", "-") {
             mod $name;
             config.shell().set_verbose(true);
             let r = cargo::call_main_without_stdin($name::execute, config,
                                                    $name::USAGE,
-                                                   args.as_slice(),
+                                                   &args,
                                                    false);
             cargo::process_executed(r, &mut **config.shell());
             return Ok(None)
@@ -128,8 +128,7 @@ fn execute(flags: Flags, config: &Config) -> CliResult<Option<()>> {
     ) }
     each_subcommand!(cmd);
 
-    execute_subcommand(command.as_slice(), args.as_slice(),
-                       &mut **config.shell());
+    execute_subcommand(&command, &args, &mut config.shell());
     Ok(None)
 }
 
@@ -139,7 +138,7 @@ fn find_closest(cmd: &str) -> Option<String> {
                             // c.lev_distance(cmd))) allows us to only make
                             // suggestions that have an edit distance of
                             // 3 or less
-                            .map(|c| (lev_distance(c.as_slice(), cmd), c))
+                            .map(|c| (lev_distance(&c, cmd), c))
                             .filter(|&(d, _): &(usize, &String)| d < 4)
                             .min_by(|&(d, _)| d) {
         Some((_, c)) => {
@@ -158,7 +157,7 @@ fn execute_subcommand(cmd: &str, args: &[String], shell: &mut MultiShell) {
                                           Did you mean `{}`?\n", closest),
                 None => "No such subcommand".to_string()
             };
-            return handle_error(CliError::new(msg, 127), shell)
+            return handle_error(CliError::new(&msg, 127), shell)
         }
     };
     let status = Command::new(command)
@@ -175,13 +174,13 @@ fn execute_subcommand(cmd: &str, args: &[String], shell: &mut MultiShell) {
         }
         Ok(ExitSignal(i)) => {
             let msg = format!("subcommand failed with signal: {}", i);
-            handle_error(CliError::new(msg, i as i32), shell)
+            handle_error(CliError::new(&msg, i as i32), shell)
         }
         Err(old_io::IoError{kind, ..}) if kind == old_io::FileNotFound =>
             handle_error(CliError::new("No such subcommand", 127), shell),
         Err(err) => handle_error(
             CliError::new(
-                format!("Subcommand failed to run: {}", err), 127),
+                &format!("Subcommand failed to run: {}", err), 127),
             shell)
     }
 }
@@ -231,7 +230,7 @@ fn is_executable(path: &Path) -> bool {
 fn find_command(cmd: &str) -> Option<Path> {
     let command_exe = format!("cargo-{}{}", cmd, env::consts::EXE_SUFFIX);
     let dirs = list_command_directory();
-    let mut command_paths = dirs.iter().map(|dir| dir.join(command_exe.as_slice()));
+    let mut command_paths = dirs.iter().map(|dir| dir.join(&command_exe));
     command_paths.find(|path| path.exists())
 }
 
index d555676786c84fa3c8a31aa417ef46c540c7ef8a..0aba6b5bb7884deca95ecbddeb0e6bc0f9c6b6ac 100644 (file)
@@ -54,7 +54,7 @@ pub fn execute(options: Options, config: &Config) -> CliResult<Option<()>> {
             jobs: options.flag_jobs,
             target: None,
             dev_deps: false,
-            features: options.flag_features.as_slice(),
+            features: &options.flag_features,
             no_default_features: options.flag_no_default_features,
             spec: options.flag_package.as_ref().map(|s| s.as_slice()),
             lib_only: false,
index 3fa251821b325cf132ceed38a7c387b795dc9f15..43f62c81d5abe4c89a2a06667646696b805686f0 100644 (file)
@@ -23,7 +23,7 @@ pub fn execute(options: Options, config: &Config) -> CliResult<Option<()>> {
     config.shell().set_verbose(options.flag_verbose);
     let Options { flag_url: url, flag_reference: reference, .. } = options;
 
-    let url = try!(url.as_slice().to_url().map_err(|e| {
+    let url = try!(url.to_url().map_err(|e| {
                        human(format!("The URL `{}` you passed was \
                                       not a valid URL: {}", url, e))
                    })
@@ -35,7 +35,7 @@ pub fn execute(options: Options, config: &Config) -> CliResult<Option<()>> {
     let mut source = GitSource::new(&source_id, config);
 
     try!(source.update().map_err(|e| {
-        CliError::new(format!("Couldn't update {:?}: {:?}", source, e), 1)
+        CliError::new(&format!("Couldn't update {:?}: {:?}", source, e), 1)
     }));
 
     Ok(None)
index 9cb44b7065c4499367e76224878ef9d7b75b376d..e716af48c6a5d6b332a645436029a951ee716f2d 100644 (file)
@@ -46,7 +46,7 @@ pub fn execute(options: Options, config: &Config) -> CliResult<Option<()>> {
         }
     };
 
-    let token = token.as_slice().trim().to_string();
+    let token = token.trim().to_string();
     try!(ops::registry_login(config, token).map_err(|e| {
         CliError::from_boxed(e, 101)
     }));
index e2412d1cf69a5d5c9691d0c8f7f23678974dcd69..4126e3826e7d0e08be8c853345433b9ebc2b8e7f 100644 (file)
@@ -35,7 +35,7 @@ pub fn execute(options: Options, config: &Config) -> CliResult<Option<()>> {
 
     let opts = ops::NewOptions {
         version_control: flag_vcs,
-        path: arg_path.as_slice(),
+        path: &arg_path,
         bin: flag_bin,
     };
 
index 4bf3303604ea17363895aa7d53e6504d1a010608..fac1f9f75ecacff685b09cf154ff1bf5a9c7d9c1 100644 (file)
@@ -18,7 +18,7 @@ Options:
 ";
 
 pub fn execute(options: Options, config: &Config) -> CliResult<Option<Package>> {
-    let path = Path::new(options.flag_manifest_path.as_slice());
+    let path = Path::new(&options.flag_manifest_path);
     let mut source = try!(PathSource::for_path(&path, config).map_err(|e| {
         CliError::new(e.description(), 1)
     }));
index da295a4cc7bc63c83a1189373adb743ef69e20be..57fadbb079ca6dc3b18f3eb21e537349e78d66c1 100644 (file)
@@ -61,7 +61,7 @@ pub fn execute(options: Options, config: &Config) -> CliResult<Option<()>> {
         jobs: options.flag_jobs,
         target: options.flag_target.as_ref().map(|t| t.as_slice()),
         dev_deps: true,
-        features: options.flag_features.as_slice(),
+        features: &options.flag_features,
         no_default_features: options.flag_no_default_features,
         spec: None,
         lib_only: false,
@@ -80,7 +80,7 @@ pub fn execute(options: Options, config: &Config) -> CliResult<Option<()>> {
                             target_kind,
                             name,
                             &compile_opts,
-                            options.arg_args.as_slice()).map_err(|err| {
+                            &options.arg_args).map_err(|err| {
         CliError::from_boxed(err, 101)
     }));
     match err {
index 27901d6ea4ce4f1d276b801bb20020a2e6e7f96c..63dbaf73ea17916393c229acf8ae07f5ff880347 100644 (file)
@@ -28,7 +28,7 @@ pub fn execute(options: Options, config: &Config) -> CliResult<Option<()>> {
         ..
     } = options;
 
-    ops::search(query.as_slice(), config, host)
+    ops::search(&query, config, host)
         .map(|_| None)
         .map_err(|err| CliError::from_boxed(err, 101))
 }
index 1e27d4465b45854b521719f394a154745e63534c..ef326719ec830c7d02f28140507a999ec8bb7abd 100644 (file)
@@ -63,7 +63,7 @@ pub fn execute(options: Options, config: &Config) -> CliResult<Option<()>> {
             jobs: options.flag_jobs,
             target: options.flag_target.as_ref().map(|s| s.as_slice()),
             dev_deps: true,
-            features: options.flag_features.as_slice(),
+            features: &options.flag_features,
             no_default_features: options.flag_no_default_features,
             spec: options.flag_package.as_ref().map(|s| s.as_slice()),
             lib_only: false,
@@ -72,7 +72,7 @@ pub fn execute(options: Options, config: &Config) -> CliResult<Option<()>> {
     };
 
     let err = try!(ops::run_tests(&root, &ops,
-                                  options.arg_args.as_slice()).map_err(|err| {
+                                  &options.arg_args).map_err(|err| {
         CliError::from_boxed(err, 101)
     }));
     match err {
index b204db3395271749acd1fd52efd48c581eebac36..e93287f75b32ab8ee57978586ea164f79ff5299f 100644 (file)
@@ -71,9 +71,7 @@ impl Dependency {
         self.specified_req.as_ref().map(|s| s.as_slice())
     }
 
-    pub fn get_name(&self) -> &str {
-        self.name.as_slice()
-    }
+    pub fn get_name(&self) -> &str { &self.name }
 
     /// Returns the place where this dependency must be searched for.
     pub fn get_source_id(&self) -> &SourceId {
@@ -144,7 +142,7 @@ impl Dependency {
     /// Returns true if the default features of the dependency are requested.
     pub fn uses_default_features(&self) -> bool { self.default_features }
     /// Returns the list of features that are requested by the dependency.
-    pub fn get_features(&self) -> &[String] { self.features.as_slice() }
+    pub fn get_features(&self) -> &[String] { &self.features }
 
     /// Returns true if the package (`sum`) can fulfill this dependency request.
     pub fn matches(&self, sum: &Summary) -> bool {
@@ -153,7 +151,7 @@ impl Dependency {
 
     /// Returns true if the package (`id`) can fulfill this dependency request.
     pub fn matches_id(&self, id: &PackageId) -> bool {
-        self.name.as_slice() == id.get_name() &&
+        self.name == id.get_name() &&
             (self.only_match_name || (self.req.matches(id.get_version()) &&
                                       &self.source_id == id.get_source_id()))
     }
@@ -168,7 +166,7 @@ impl Dependency {
     pub fn is_active_for_platform(&self, platform: &str) -> bool {
         match self.only_for_platform {
             None => true,
-            Some(ref p) if p.as_slice() == platform => true,
+            Some(ref p) if *p == platform => true,
             _ => false
         }
     }
index 424eb5a35a2f841a68fda79fe2c15ddedbbd3c18..b3d13f1244f951108f52f57353c21f5dddd5f572 100644 (file)
@@ -88,10 +88,6 @@ impl LibKind {
         }
     }
 
-    pub fn from_strs<S: Str>(strings: Vec<S>) -> CargoResult<Vec<LibKind>> {
-        strings.iter().map(|s| LibKind::from_str(s.as_slice())).collect()
-    }
-
     /// Returns the argument suitable for `--crate-type` to pass to rustc.
     pub fn crate_type(&self) -> &'static str {
         match *self {
@@ -201,7 +197,7 @@ impl Profile {
     }
 
     pub fn is_compile(&self) -> bool {
-        self.env.as_slice() == "compile"
+        self.env == "compile"
     }
 
     pub fn is_doc(&self) -> bool {
@@ -250,7 +246,7 @@ impl Profile {
     }
 
     pub fn get_env(&self) -> &str {
-        self.env.as_slice()
+        &self.env
     }
 
     pub fn get_dest(&self) -> Option<&str> {
@@ -422,7 +418,7 @@ impl Manifest {
     }
 
     pub fn get_targets(&self) -> &[Target] {
-        self.targets.as_slice()
+        &self.targets
     }
 
     pub fn get_target_dir(&self) -> &Path {
@@ -442,15 +438,15 @@ impl Manifest {
     }
 
     pub fn get_warnings(&self) -> &[String] {
-        self.warnings.as_slice()
+        &self.warnings
     }
 
     pub fn get_exclude(&self) -> &[String] {
-        self.exclude.as_slice()
+        &self.exclude
     }
 
     pub fn get_include(&self) -> &[String] {
-        self.include.as_slice()
+        &self.include
     }
 
     pub fn get_metadata(&self) -> &ManifestMetadata { &self.metadata }
@@ -541,7 +537,7 @@ impl Target {
     }
 
     pub fn get_name(&self) -> &str {
-        self.name.as_slice()
+        &self.name
     }
 
     pub fn get_src_path(&self) -> &Path {
index 8216c66bdae8b3f4729f1f0097d404ebdd6a5e24..118cb9e4d3776a4074d2c32e113e73868e06b1bf 100644 (file)
@@ -168,7 +168,7 @@ impl PackageSet {
     }
 
     pub fn get_packages(&self) -> &[Package] {
-        self.packages.as_slice()
+        &self.packages
     }
 
     // For now, assume that the package set contains only one package with a
@@ -181,7 +181,7 @@ impl PackageSet {
                 .map(|dep| dep.get_name())
                 .collect();
 
-            graph.add(pkg.get_name(), deps.as_slice());
+            graph.add(pkg.get_name(), &deps);
         }
 
         let pkgs = match graph.sort() {
index 0e1825adbba66c6ee38f5d3a2eec34b779a410f0..29a4ce14105a0b76cc629e2e4c49bb1c6b2e8f2b 100644 (file)
@@ -38,7 +38,7 @@ impl Decodable for PackageId {
     fn decode<D: Decoder>(d: &mut D) -> Result<PackageId, D::Error> {
         let string: String = try!(Decodable::decode(d));
         let regex = Regex::new(r"^([^ ]+) ([^ ]+) \(([^\)]+)\)$").unwrap();
-        let captures = regex.captures(string.as_slice()).expect("invalid serialized PackageId");
+        let captures = regex.captures(&string).expect("invalid serialized PackageId");
 
         let name = captures.at(1).unwrap();
         let version = captures.at(2).unwrap();
@@ -132,7 +132,7 @@ impl PackageId {
     }
 
     pub fn get_name(&self) -> &str {
-        self.inner.name.as_slice()
+        &self.inner.name
     }
 
     pub fn get_version(&self) -> &semver::Version {
@@ -145,7 +145,7 @@ impl PackageId {
 
     pub fn generate_metadata(&self) -> Metadata {
         let metadata = short_hash(
-            &(self.inner.name.as_slice(), self.inner.version.to_string(),
+            &(&self.inner.name, self.inner.version.to_string(),
               &self.inner.source_id));
         let extra_filename = format!("-{}", metadata);
 
@@ -165,7 +165,7 @@ impl PackageId {
 
 impl Metadata {
     pub fn mix<T: Hash<SipHasher>>(&mut self, t: &T) {
-        let new_metadata = short_hash(&(self.metadata.as_slice(), t));
+        let new_metadata = short_hash(&(&self.metadata, t));
         self.extra_filename = format!("-{}", new_metadata);
         self.metadata = new_metadata;
     }
index b20f8320df77da91c2191e95e3aed51e5315505f..8d2e6ed5e9bd9824688b5e00c59e0639755c4a42 100644 (file)
@@ -20,13 +20,13 @@ impl PackageIdSpec {
                 Err(..) => {}
             }
             if !spec.contains("://") {
-                match url(format!("cargo://{}", spec).as_slice()) {
+                match url(&format!("cargo://{}", spec)) {
                     Ok(url) => return PackageIdSpec::from_url(url),
                     Err(..) => {}
                 }
             }
         }
-        let mut parts = spec.as_slice().splitn(1, ':');
+        let mut parts = spec.splitn(1, ':');
         let name = parts.next().unwrap();
         let version = match parts.next() {
             Some(version) => Some(try!(Version::parse(version).map_err(human))),
@@ -69,7 +69,7 @@ impl PackageIdSpec {
             }));
             match frag {
                 Some(fragment) => {
-                    let mut parts = fragment.as_slice().splitn(1, ':');
+                    let mut parts = fragment.splitn(1, ':');
                     let name_or_version = parts.next().unwrap();
                     match parts.next() {
                         Some(part) => {
@@ -97,7 +97,7 @@ impl PackageIdSpec {
         })
     }
 
-    pub fn get_name(&self) -> &str { self.name.as_slice() }
+    pub fn get_name(&self) -> &str { &self.name }
     pub fn get_version(&self) -> Option<&Version> { self.version.as_ref() }
     pub fn get_url(&self) -> Option<&Url> { self.url.as_ref() }
 
@@ -134,7 +134,7 @@ impl fmt::Display for PackageIdSpec {
         let mut printed_name = false;
         match self.url {
             Some(ref url) => {
-                if url.scheme.as_slice() == "cargo" {
+                if url.scheme == "cargo" {
                     try!(write!(f, "{}/{}", url.host().unwrap(),
                                 url.path().unwrap().connect("/")));
                 } else {
@@ -169,7 +169,7 @@ mod tests {
         fn ok(spec: &str, expected: PackageIdSpec) {
             let parsed = PackageIdSpec::parse(spec).unwrap();
             assert_eq!(parsed, expected);
-            assert_eq!(parsed.to_string().as_slice(), spec);
+            assert_eq!(parsed.to_string(), spec);
         }
 
         ok("http://crates.io/foo#1.2.3", PackageIdSpec {
index 87fd72ec766132361901c0324188bffe6e96cf66..dedf2cb798817e3aee6c6100a95fcb28023c4a43 100644 (file)
@@ -89,8 +89,8 @@ pub struct EncodableDependency {
 impl EncodableDependency {
     fn to_package_id(&self, default_source: &SourceId) -> CargoResult<PackageId> {
         PackageId::new(
-            self.name.as_slice(),
-            self.version.as_slice(),
+            &self.name,
+            &self.version,
             self.source.as_ref().unwrap_or(default_source))
     }
 }
@@ -106,7 +106,7 @@ impl Encodable for EncodablePackageId {
     fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
         let mut out = format!("{} {}", self.name, self.version);
         if let Some(ref s) = self.source {
-            out.push_str(format!(" ({})", s.to_url()).as_slice());
+            out.push_str(&format!(" ({})", s.to_url()));
         }
         out.encode(s)
     }
@@ -116,7 +116,7 @@ impl Decodable for EncodablePackageId {
     fn decode<D: Decoder>(d: &mut D) -> Result<EncodablePackageId, D::Error> {
         let string: String = try!(Decodable::decode(d));
         let regex = Regex::new(r"^([^ ]+) ([^ ]+)(?: \(([^\)]+)\))?$").unwrap();
-        let captures = regex.captures(string.as_slice())
+        let captures = regex.captures(&string)
                             .expect("invalid serialized PackageId");
 
         let name = captures.at(1).unwrap();
@@ -137,8 +137,8 @@ impl Decodable for EncodablePackageId {
 impl EncodablePackageId {
     fn to_package_id(&self, default_source: &SourceId) -> CargoResult<PackageId> {
         PackageId::new(
-            self.name.as_slice(),
-            self.version.as_slice(),
+            &self.name,
+            &self.version,
             self.source.as_ref().unwrap_or(default_source))
     }
 }
index a22964504b386bc7be28c3c7d076b5fccdf853ff..846148d4ba9125e46833c8edc8c136c7044b0b3d 100644 (file)
@@ -99,12 +99,11 @@ impl Resolve {
             }
             for id in ids.iter() {
                 if version_cnt[id.get_version()] == 1 {
-                    msg.push_str(format!("\n  {}:{}", spec.get_name(),
-                                 id.get_version()).as_slice());
+                    msg.push_str(&format!("\n  {}:{}", spec.get_name(),
+                                          id.get_version()));
                 } else {
-                    msg.push_str(format!("\n  {}",
-                                         PackageIdSpec::from_package_id(*id))
-                                        .as_slice());
+                    msg.push_str(&format!("\n  {}",
+                                          PackageIdSpec::from_package_id(*id)));
                 }
             }
         }
@@ -248,7 +247,7 @@ fn activate_deps<'a>(cx: Box<Context>,
                      cur: usize) -> CargoResult<CargoResult<Box<Context>>> {
     if cur == deps.len() { return Ok(Ok(cx)) }
     let (dep, ref candidates, ref features) = deps[cur];
-    let method = Method::Required(false, features.as_slice(),
+    let method = Method::Required(false, &features,
                                   dep.uses_default_features(), platform);
 
     let key = (dep.get_name().to_string(), dep.get_source_id().clone());
@@ -343,13 +342,13 @@ fn activation_error(cx: &Context,
                 for edge in edges {
                     if edge != v.get_package_id() { continue }
 
-                    msg.push_str(format!("\n  version {} in use by {}",
-                                         v.get_version(), edge).as_slice());
+                    msg.push_str(&format!("\n  version {} in use by {}",
+                                          v.get_version(), edge));
                     continue 'outer;
                 }
             }
-            msg.push_str(format!("\n  version {} in use by ??",
-                                 v.get_version()).as_slice());
+            msg.push_str(&format!("\n  version {} in use by ??",
+                                  v.get_version()));
         }
 
         msg.push_str(&format!("\n  possible versions to select: {}",
@@ -386,7 +385,7 @@ fn activation_error(cx: &Context,
         msg.push_str("\nversions found: ");
         for (i, c) in candidates.iter().take(3).enumerate() {
             if i != 0 { msg.push_str(", "); }
-            msg.push_str(c.get_version().to_string().as_slice());
+            msg.push_str(&c.get_version().to_string());
         }
         if candidates.len() > 3 {
             msg.push_str(", ...");
@@ -436,7 +435,7 @@ fn resolve_features<'a>(cx: &mut Context, parent: &'a Summary,
     let deps = deps.filter(|d| {
         match method {
             Method::Required(_, _, _, Some(ref platform)) => {
-                d.is_active_for_platform(platform.as_slice())
+                d.is_active_for_platform(platform)
             },
             _ => true
         }
@@ -455,7 +454,7 @@ fn resolve_features<'a>(cx: &mut Context, parent: &'a Summary,
         let mut base = feature_deps.remove(dep.get_name()).unwrap_or(vec![]);
         for feature in dep.get_features().iter() {
             base.push(feature.clone());
-            if feature.as_slice().contains("/") {
+            if feature.contains("/") {
                 return Err(human(format!("features in dependencies \
                                           cannot enable features in \
                                           other dependencies: `{}`",
@@ -508,8 +507,7 @@ fn build_features(s: &Summary, method: Method)
     match method {
         Method::Everything => {
             for key in s.get_features().keys() {
-                try!(add_feature(s, key.as_slice(), &mut deps, &mut used,
-                                 &mut visited));
+                try!(add_feature(s, key, &mut deps, &mut used, &mut visited));
             }
             for dep in s.get_dependencies().iter().filter(|d| d.is_optional()) {
                 try!(add_feature(s, dep.get_name(), &mut deps, &mut used,
@@ -518,8 +516,7 @@ fn build_features(s: &Summary, method: Method)
         }
         Method::Required(_, requested_features, _, _) =>  {
             for feat in requested_features.iter() {
-                try!(add_feature(s, feat.as_slice(), &mut deps, &mut used,
-                                 &mut visited));
+                try!(add_feature(s, feat, &mut deps, &mut used, &mut visited));
             }
         }
     }
@@ -567,7 +564,7 @@ fn build_features(s: &Summary, method: Method)
                 match s.get_features().get(feat) {
                     Some(recursive) => {
                         for f in recursive.iter() {
-                            try!(add_feature(s, f.as_slice(), deps, used,
+                            try!(add_feature(s, f, deps, used,
                                              visited));
                         }
                     }
index c0a62baaf1e32b87e8274c5f6a499ca97b51d8ef..775e73e77839be1bc9e516a1c144196ccfa308a2 100644 (file)
@@ -121,7 +121,7 @@ impl Shell {
     pub fn say<T: ToString>(&mut self, message: T, color: Color) -> IoResult<()> {
         try!(self.reset());
         if color != BLACK { try!(self.fg(color)); }
-        try!(self.write_line(message.to_string().as_slice()));
+        try!(self.write_line(&message.to_string()));
         try!(self.reset());
         try!(self.flush());
         Ok(())
@@ -134,9 +134,9 @@ impl Shell {
         try!(self.reset());
         if color != BLACK { try!(self.fg(color)); }
         if self.supports_attr(Attr::Bold) { try!(self.attr(Attr::Bold)); }
-        try!(self.write_str(format!("{:>12}", status).as_slice()));
+        try!(self.write_str(&format!("{:>12}", status)));
         try!(self.reset());
-        try!(self.write_line(format!(" {}", message).as_slice()));
+        try!(self.write_line(&format!(" {}", message)));
         try!(self.flush());
         Ok(())
     }
index 089a38890a4b91259135d3da8be5172113d53eee..3c65098e6a973b0b0c11f073f45da88b0f68bc64 100644 (file)
@@ -98,7 +98,7 @@ impl SourceId {
     ///                     656c58fb7c5ef5f12bc747f".to_string());
     /// ```
     pub fn from_url(string: String) -> SourceId {
-        let mut parts = string.as_slice().splitn(1, '+');
+        let mut parts = string.splitn(1, '+');
         let kind = parts.next().unwrap();
         let url = parts.next().unwrap();
 
@@ -339,7 +339,7 @@ impl GitReference {
     pub fn to_ref_string(&self) -> Option<String> {
         match *self {
             GitReference::Branch(ref s) => {
-                if s.as_slice() == "master" {
+                if *s == "master" {
                     None
                 } else {
                     Some(format!("branch={}", s))
@@ -460,7 +460,7 @@ impl<'src> Source for SourceSet<'src> {
         let mut ret = Vec::new();
 
         for source in self.sources.iter() {
-            ret.push_all(try!(source.get(packages)).as_slice());
+            ret.extend(try!(source.get(packages)).into_iter());
         }
 
         Ok(ret)
index 1544f030ac69c4ced7640d90053ea4f1ddc03116..185e85c20ad1987c97dbb5a4071d357bece01228 100644 (file)
@@ -34,7 +34,7 @@ impl Summary {
         }
         for (feature, list) in features.iter() {
             for dep in list.iter() {
-                let mut parts = dep.as_slice().splitn(1, '/');
+                let mut parts = dep.splitn(1, '/');
                 let dep = parts.next().unwrap();
                 let is_reexport = parts.next().is_some();
                 if !is_reexport && features.get(dep).is_some() { continue }
@@ -85,7 +85,7 @@ impl Summary {
     }
 
     pub fn get_dependencies(&self) -> &[Dependency] {
-        self.dependencies.as_slice()
+        &self.dependencies
     }
 
     pub fn get_features(&self) -> &HashMap<String, Vec<String>> {
index 9e2e0f85f41d2cc3c6e3144b1446ec1b2ddc5242..609e1bd84baed243c4cac37a17358c562c61e9e8 100644 (file)
@@ -225,7 +225,7 @@ fn json_from_stdin<T: Decodable>() -> CliResult<T> {
         CliError::new("Standard in did not exist or was not UTF-8", 1)
     }));
 
-    let json = try!(Json::from_str(input.as_slice()).map_err(|_| {
+    let json = try!(Json::from_str(&input).map_err(|_| {
         CliError::new("Could not parse standard in as JSON", 1)
     }));
     let mut decoder = json::Decoder::new(json);
index 97826ccf683a60121705c2c6d1c124f691bc25e1..f44194171c4aa7f5d02b6318ad35a9daa6d40d2c 100644 (file)
@@ -59,7 +59,6 @@ pub fn clean(manifest_path: &Path, opts: &CleanOptions) -> CargoResult<()> {
         try!(rm_rf(&layout.native(&pkg)));
         try!(rm_rf(&layout.fingerprint(&pkg)));
         for filename in try!(cx.target_filenames(target)).iter() {
-            let filename = filename.as_slice();
             try!(rm_rf(&layout.dest().join(filename)));
             try!(rm_rf(&layout.deps().join(filename)));
         }
index a0fea0f37fb1a65ece184a51895ff9dbc8ff23c7..6856c6108a6e3f2f5079f80785a08e11875ef42f 100644 (file)
@@ -80,7 +80,7 @@ pub fn compile_pkg(package: &Package, options: &CompileOptions)
 
     let target = target.map(|s| s.to_string());
     let features = features.iter().flat_map(|s| {
-        s.as_slice().split(' ')
+        s.split(' ')
     }).map(|s| s.to_string()).collect::<Vec<String>>();
 
     if spec.is_some() && (no_default_features || features.len() > 0) {
@@ -110,7 +110,7 @@ pub fn compile_pkg(package: &Package, options: &CompileOptions)
         try!(registry.add_overrides(override_ids));
 
         let platform = target.as_ref().map(|e| e.as_slice()).or(Some(rustc_host.as_slice()));
-        let method = Method::Required(dev_deps, features.as_slice(),
+        let method = Method::Required(dev_deps, &features,
                                       !no_default_features, platform);
         let resolved_with_overrides =
                 try!(ops::resolve_with_previous(&mut registry, package, method,
@@ -119,7 +119,7 @@ pub fn compile_pkg(package: &Package, options: &CompileOptions)
         let req: Vec<PackageId> = resolved_with_overrides.iter().map(|r| {
             r.clone()
         }).collect();
-        let packages = try!(registry.get(req.as_slice()).chain_error(|| {
+        let packages = try!(registry.get(&req).chain_error(|| {
             human("Unable to get packages from source")
         }));
 
@@ -150,8 +150,8 @@ pub fn compile_pkg(package: &Package, options: &CompileOptions)
         let _p = profile::start("compiling");
         let lib_overrides = try!(scrape_build_config(config, jobs, target));
 
-        try!(ops::compile_targets(env.as_slice(), targets.as_slice(), to_build,
-                                  &PackageSet::new(packages.as_slice()),
+        try!(ops::compile_targets(&env, &targets, to_build,
+                                  &PackageSet::new(&packages),
                                   &resolve_with_overrides, &sources,
                                   config, lib_overrides, exec_engine.clone()))
     };
@@ -176,7 +176,7 @@ fn source_ids_from_config(config: &Config, cur_path: Path)
         // The path listed next to the string is the config file in which the
         // key was located, so we want to pop off the `.cargo/config` component
         // to get the directory containing the `.cargo` folder.
-        p.dir_path().dir_path().join(s.as_slice())
+        p.dir_path().dir_path().join(s)
     }).filter(|p| {
         // Make sure we don't override the local package, even if it's in the
         // list of override paths.
@@ -248,7 +248,7 @@ fn scrape_target_config(config: &Config, triple: &str)
             if k == "rustc-flags" {
                 let whence = format!("in `{}` (in {:?})", key, path);
                 let (paths, links) = try!(
-                    BuildOutput::parse_rustc_flags(v.as_slice(), &whence[])
+                    BuildOutput::parse_rustc_flags(&v, &whence[])
                 );
                 output.library_paths.extend(paths.into_iter());
                 output.library_links.extend(links.into_iter());
index a2bafbc34cf2e3602b1e7e87704f8358c71d3cca..09d83185af1f047c64e9c79f4e7ed9e6543628ee 100644 (file)
@@ -26,7 +26,7 @@ impl Decodable for VersionControl {
             "none" => VersionControl::NoVcs,
             n => {
                 let err = format!("could not decode '{}' as version control", n);
-                return Err(d.error(err.as_slice()));
+                return Err(d.error(&err));
             }
         })
     }
@@ -48,8 +48,8 @@ pub fn new(opts: NewOptions, config: &Config) -> CargoResult<()> {
     for c in name.chars() {
         if c.is_alphanumeric() { continue }
         if c == '_' || c == '-' { continue }
-        return Err(human(format!("Invalid character `{}` in crate name: `{}`",
-                                 c, name).as_slice()));
+        return Err(human(&format!("Invalid character `{}` in crate name: `{}`",
+                                  c, name)));
     }
     mk(config, &path, name, &opts).chain_error(|| {
         human(format!("Failed to create project `{}` at `{}`",
@@ -102,13 +102,13 @@ fn mk(config: &Config, path: &Path, name: &str,
         (None, None, name, None) => name,
     };
 
-    try!(File::create(&path.join("Cargo.toml")).write_str(format!(
+    try!(File::create(&path.join("Cargo.toml")).write_str(&format!(
 r#"[package]
 
 name = "{}"
 version = "0.0.1"
 authors = ["{}"]
-"#, name, author).as_slice()));
+"#, name, author)));
 
     try!(fs::mkdir(&path.join("src"), old_io::USER_RWX));
 
@@ -146,8 +146,8 @@ fn discover_author() -> CargoResult<(String, Option<String>)> {
     };
     let email = git_config.and_then(|g| g.get_str("user.email").ok());
 
-    let name = name.as_slice().trim().to_string();
-    let email = email.map(|s| s.as_slice().trim().to_string());
+    let name = name.trim().to_string();
+    let email = email.map(|s| s.trim().to_string());
 
     Ok((name, email))
 }
index 07d83e038ea473303ce36dada1412b4ff29f4811..f38b1e909cbdeb37c106743f460d5220ddb61b01 100644 (file)
@@ -88,16 +88,17 @@ fn check_metadata(pkg: &Package, config: &Config) -> CargoResult<()> {
 
     if !missing.is_empty() {
         let mut things = missing[..missing.len() - 1].connect(", ");
-        // things will be empty if and only if length == 1 (i.e. the only case to have no `or`).
+        // things will be empty if and only if length == 1 (i.e. the only case
+        // to have no `or`).
         if !things.is_empty() {
             things.push_str(" or ");
         }
-        things.push_str(missing.last().unwrap().as_slice());
+        things.push_str(&missing.last().unwrap());
 
         try!(config.shell().warn(
-            format!("warning: manifest has no {things}. \
+            &format!("warning: manifest has no {things}. \
                     See http://doc.crates.io/manifest.html#package-metadata for more info.",
-                    things = things).as_slice()))
+                    things = things)))
     }
     Ok(())
 }
@@ -130,11 +131,11 @@ fn tar(pkg: &Package, src: &PathSource, config: &Config,
         }));
         let mut file = try!(File::open(file));
         try!(config.shell().verbose(|shell| {
-            shell.status("Archiving", relative.as_slice())
+            shell.status("Archiving", &relative)
         }));
         let path = format!("{}-{}{}{}", pkg.get_name(),
                            pkg.get_version(), old_path::SEP, relative);
-        try!(ar.append(path.as_slice(), &mut file).chain_error(|| {
+        try!(ar.append(&path, &mut file).chain_error(|| {
             internal(format!("could not archive source file `{}`", relative))
         }));
     }
index 27c8c42aa1d74a2aa7ed929d352ec0646d550449..f381f7a1a89a91e9c3dc5e1fcf0d7242ad41a0ef 100644 (file)
@@ -26,7 +26,7 @@ pub fn read_package(path: &Path, source_id: &SourceId, config: &Config)
 
     let layout = project_layout(&path.dir_path());
     let (manifest, nested) =
-        try!(read_manifest(data.as_slice(), layout, source_id, config));
+        try!(read_manifest(&data, layout, source_id, config));
 
     Ok((Package::new(manifest, path, source_id), nested))
 }
index 883b7f0a442e53b61f024d3ef0f0d4714e075a18..e1060432ba6c320f884af181108b415056d5f6f3 100644 (file)
@@ -21,7 +21,7 @@ pub fn run(manifest_path: &Path,
             TargetKind::Example => a.is_example(),
             TargetKind::Lib(_) => false,
         };
-        let matches_name = name.as_ref().map_or(true, |n| n.as_slice() == a.get_name());
+        let matches_name = name.as_ref().map_or(true, |n| *n == a.get_name());
         matches_kind && matches_name && a.get_profile().get_env() == env &&
             !a.get_profile().is_custom_build()
     });
index 3a220cfc4ea1f7a7d89a90bfc44a8f1fdd764688..74a7f4220e45149546fddad94d1f46e3e9d082fd 100644 (file)
@@ -95,12 +95,12 @@ impl Compilation {
         }
         search_path.push(self.root_output.clone());
         search_path.push(self.deps_output.clone());
-        let search_path = try!(util::join_paths(search_path.as_slice(),
+        let search_path = try!(util::join_paths(&search_path,
                                                 DynamicLibrary::envvar()));
         let mut cmd = try!(CommandPrototype::new(cmd)).env(
-            DynamicLibrary::envvar(), Some(search_path.as_slice()));
+            DynamicLibrary::envvar(), Some(&search_path));
         for (k, v) in self.extra_env.iter() {
-            cmd = cmd.env(k.as_slice(), v.as_ref().map(|s| s.as_slice()));
+            cmd = cmd.env(k, v.as_ref());
         }
 
         Ok(cmd.env("CARGO_MANIFEST_DIR", Some(pkg.get_manifest_path().dir_path()))
@@ -127,7 +127,7 @@ fn pre_version_component(v: &Version) -> Option<String> {
 
     for (i, x) in v.pre.iter().enumerate() {
         if i != 0 { ret.push('.') };
-        ret.push_str(x.to_string().as_slice());
+        ret.push_str(&x.to_string());
     }
 
     Some(ret)
index 960e1e38ffbb7a6a16459de7b4b3fa939fbc070a..ee37027befca9ad1da2fd86339983bba1aee2382 100644 (file)
@@ -102,8 +102,8 @@ impl<'a, 'b: 'a> Context<'a, 'b> {
         };
         let output = try!(process.exec_with_output());
 
-        let error = str::from_utf8(output.error.as_slice()).unwrap();
-        let output = str::from_utf8(output.output.as_slice()).unwrap();
+        let error = str::from_utf8(&output.error).unwrap();
+        let output = str::from_utf8(&output.output).unwrap();
         let mut lines = output.lines();
         let nodylib = Regex::new("unsupported crate type.*dylib").unwrap();
         let nobin = Regex::new("unsupported crate type.*bin").unwrap();
@@ -236,13 +236,13 @@ impl<'a, 'b: 'a> Context<'a, 'b> {
         match *pair {
             None => return Err(human(format!("dylib outputs are not supported \
                                               for {}", triple))),
-            Some((ref s1, ref s2)) => Ok((s1.as_slice(), s2.as_slice())),
+            Some((ref s1, ref s2)) => Ok((s1, s2)),
         }
     }
 
     /// Return the target triple which this context is targeting.
     pub fn target_triple(&self) -> &str {
-        self.target_triple.as_slice()
+        &self.target_triple
     }
 
     /// Return the exact filename of the target.
@@ -254,9 +254,9 @@ impl<'a, 'b: 'a> Context<'a, 'b> {
            target.get_profile().is_test() {
             ret.push(format!("{}{}", stem,
                              if target.get_profile().is_for_host() {
-                                 self.host_exe.as_slice()
+                                 &self.host_exe
                              } else {
-                                 self.target_exe.as_slice()
+                                 &self.target_exe
                              }));
         } else {
             if target.is_dylib() {
index ada89b6e6f8266f23adee68d7a5452a148c4b717..ac90612e0dd222e66fecb19769cc1569dfd7ede2 100644 (file)
@@ -73,8 +73,7 @@ pub fn prepare(pkg: &Package, target: &Target, req: Platform,
     match cx.resolve.features(pkg.get_package_id()) {
         Some(features) => {
             for feat in features.iter() {
-                p = p.env(format!("CARGO_FEATURE_{}",
-                                  super::envify(feat.as_slice())).as_slice(),
+                p = p.env(&format!("CARGO_FEATURE_{}", super::envify(feat)),
                           Some("1"));
             }
         }
@@ -135,10 +134,9 @@ pub fn prepare(pkg: &Package, target: &Target, req: Platform,
             for &(ref name, ref id) in lib_deps.iter() {
                 let data = &build_state[(id.clone(), kind)].metadata;
                 for &(ref key, ref value) in data.iter() {
-                    p = p.env(format!("DEP_{}_{}",
-                                      super::envify(name.as_slice()),
-                                      super::envify(key.as_slice())).as_slice(),
-                              Some(value.as_slice()));
+                    p = p.env(&format!("DEP_{}_{}", super::envify(name),
+                                       super::envify(key)),
+                              Some(value));
                 }
             }
             p = try!(super::add_plugin_deps(p, &build_state, plugin_deps));
@@ -159,10 +157,10 @@ pub fn prepare(pkg: &Package, target: &Target, req: Platform,
         // This is also the location where we provide feedback into the build
         // state informing what variables were discovered via our script as
         // well.
-        let output = try!(str::from_utf8(output.output.as_slice()).chain_error(|| {
+        let output = try!(str::from_utf8(&output.output).chain_error(|| {
             human("build script output was not valid utf-8")
         }));
-        let parsed_output = try!(BuildOutput::parse(output, pkg_name.as_slice()));
+        let parsed_output = try!(BuildOutput::parse(output, &pkg_name));
         build_state.insert(id, req, parsed_output);
 
         try!(File::create(&build_output.dir_path().join("output"))
@@ -196,8 +194,7 @@ pub fn prepare(pkg: &Package, target: &Target, req: Platform,
             human(format!("failed to read cached build command output: {}", e))
         }));
         let contents = try!(f.read_to_string());
-        let output = try!(BuildOutput::parse(contents.as_slice(),
-                                             pkg_name.as_slice()));
+        let output = try!(BuildOutput::parse(&contents, &pkg_name));
         build_state.insert(id, req, output);
 
         fresh.call(tx)
@@ -283,9 +280,8 @@ impl BuildOutput {
             };
 
             if key == "rustc-flags" {
-                let whence = whence.as_slice();
                 let (libs, links) = try!(
-                    BuildOutput::parse_rustc_flags(value, whence)
+                    BuildOutput::parse_rustc_flags(value, &whence)
                 );
                 library_links.extend(links.into_iter());
                 library_paths.extend(libs.into_iter());
index 9998e0e7bd8cfbe96bdff9bc984c54af032ba488..5c6a0efdd20aad44623b8abd1d169fab877637ad 100644 (file)
@@ -64,7 +64,7 @@ impl CommandPrototype {
     }
 
     pub fn get_args(&self) -> &[CString] {
-        self.args.as_slice()
+        &self.args
     }
 
     pub fn cwd(mut self, path: Path) -> CommandPrototype {
@@ -106,7 +106,7 @@ impl CommandPrototype {
             builder = builder.arg(arg);
         }
         for (key, val) in self.env.into_iter() {
-            builder = builder.env(key.as_slice(), val.as_ref());
+            builder = builder.env(&key, val.as_ref());
         }
 
         builder = builder.cwd(self.cwd);
index c2879d060864ae1098e6d32386436742af5845dc..aa510e94c754df2e2ad9923989677e1243aee4c9 100644 (file)
@@ -288,7 +288,7 @@ fn prepare(is_fresh: bool, loc: Path, fingerprint: Fingerprint) -> Preparation {
         let fingerprint = try!(fingerprint.resolve(true).chain_error(|| {
             internal("failed to resolve a pending fingerprint")
         }));
-        try!(File::create(&loc).write_str(fingerprint.as_slice()));
+        try!(File::create(&loc).write_str(&fingerprint));
         Ok(())
     });
 
@@ -321,7 +321,7 @@ fn is_fresh(loc: &Path, new_fingerprint: &Fingerprint) -> CargoResult<bool> {
     trace!("old fingerprint: {}", old_fingerprint);
     trace!("new fingerprint: {}", new_fingerprint);
 
-    Ok(old_fingerprint.as_slice() == new_fingerprint)
+    Ok(old_fingerprint == new_fingerprint)
 }
 
 fn calculate_target_mtime(dep_info: &Path) -> CargoResult<Option<u64>> {
@@ -336,7 +336,6 @@ fn calculate_target_mtime(dep_info: &Path) -> CargoResult<Option<u64>> {
         Some(Ok(line)) => line,
         _ => return Ok(None),
     };
-    let line = line.as_slice();
     let mtime = try!(fs::stat(dep_info)).modified;
     let pos = try!(line.find_str(": ").chain_error(|| {
         internal(format!("dep-info not in an understood format: {}",
@@ -350,12 +349,12 @@ fn calculate_target_mtime(dep_info: &Path) -> CargoResult<Option<u64>> {
             Some(s) => s.to_string(),
             None => break,
         };
-        while file.as_slice().ends_with("\\") {
+        while file.ends_with("\\") {
             file.pop();
             file.push(' ');
             file.push_str(deps.next().unwrap())
         }
-        match fs::stat(&cwd.join(file.as_slice())) {
+        match fs::stat(&cwd.join(&file)) {
             Ok(stat) if stat.modified <= mtime => {}
             Ok(stat) => {
                 info!("stale: {} -- {} vs {}", file, stat.modified, mtime);
index e10363ddb01d6d5a9da63b9dc5d36c63f162106e..c6eb99a526c0d6b17be4f5e6656790c91a7c50b8 100644 (file)
@@ -65,7 +65,7 @@ pub fn rustc_old_version() -> CargoResult<(String, String)> {
         internal("rustc -v didn't return utf8 output")
     }));
     let triple = {
-        let triple = output.as_slice().lines().filter(|l| {
+        let triple = output.lines().filter(|l| {
             l.starts_with("host: ")
         }).map(|l| &l[6..]).next();
         let triple = try!(triple.chain_error(|| {
@@ -84,7 +84,7 @@ pub fn rustc_new_version() -> CargoResult<(String, String)> {
         internal("rustc -v didn't return utf8 output")
     }));
     let triple = {
-        let triple = output.as_slice().lines().filter(|l| {
+        let triple = output.lines().filter(|l| {
             l.starts_with("host: ")
         }).map(|l| &l[6..]).next();
         let triple = try!(triple.chain_error(|| {
@@ -178,7 +178,7 @@ pub fn compile_targets<'a, 'b>(env: &str,
         }
 
         let compiled = compiled.contains(dep.get_package_id());
-        try!(compile(targets.as_slice(), dep, compiled, &mut cx, &mut queue));
+        try!(compile(&targets, dep, compiled, &mut cx, &mut queue));
     }
 
     try!(compile(targets, pkg, true, &mut cx, &mut queue));
@@ -418,7 +418,7 @@ fn rustc(package: &Package, target: &Target,
             }
             if pass_l_flag && id == *current_id {
                 for name in output.library_links.iter() {
-                    rustc = rustc.arg("-l").arg(name.as_slice());
+                    rustc = rustc.arg("-l").arg(name);
                 }
             }
         }
@@ -478,7 +478,7 @@ fn prepare_rustc(package: &Package, target: &Target, crate_types: Vec<&str>,
                  cx: &Context, req: Platform)
                  -> CargoResult<Vec<(CommandPrototype, Kind)>> {
     let base = try!(process(CommandType::Rustc, package, target, cx));
-    let base = build_base_args(cx, base, package, target, crate_types.as_slice());
+    let base = build_base_args(cx, base, package, target, &crate_types);
 
     let target_cmd = build_plugin_args(base.clone(), cx, package, target, Kind::Target);
     let plugin_cmd = build_plugin_args(base, cx, package, target, Kind::Host);
@@ -729,7 +729,7 @@ fn build_deps_args(mut cmd: CommandPrototype, target: &Target, package: &Package
             v.push_all(layout.root().as_vec());
             v.push(old_path::SEP_BYTE);
             v.push_all(filename.as_bytes());
-            cmd = cmd.arg("--extern").arg(v.as_slice());
+            cmd = cmd.arg("--extern").arg(&v);
         }
         return Ok(cmd);
     }
@@ -745,10 +745,9 @@ pub fn process(cmd: CommandType, pkg: &Package, _target: &Target,
 
     // We want to use the same environment and such as normal processes, but we
     // want to override the dylib search path with the one we just calculated.
-    let search_path = try!(join_paths(search_path.as_slice(),
-                                      DynamicLibrary::envvar()));
+    let search_path = try!(join_paths(&search_path, DynamicLibrary::envvar()));
     Ok(try!(cx.compilation.process(cmd, pkg))
-              .env(DynamicLibrary::envvar(), Some(search_path.as_slice())))
+              .env(DynamicLibrary::envvar(), Some(&search_path)))
 }
 
 fn each_dep<'a, F>(pkg: &Package, cx: &'a Context, mut f: F)
index 6560d5503b1ea79a9b0d9d003e3af519b79edc5b..f990340d0cf5f98e89b0fcff7e68d6d18db3e547 100644 (file)
@@ -24,7 +24,7 @@ pub fn run_tests(manifest_path: &Path,
 
     let target_name = options.name;
     let tests_to_run = compile.tests.iter().filter(|&&(ref test_name, _)| {
-        target_name.map_or(true, |target_name| target_name == test_name.as_slice())
+        target_name.map_or(true, |target_name| target_name == *test_name)
     });
 
     let cwd = config.cwd();
@@ -77,7 +77,7 @@ pub fn run_tests(manifest_path: &Path,
                 let mut arg = pkg.get_name().as_bytes().to_vec();
                 arg.push(b'=');
                 arg.push_all(lib.as_vec());
-                p = p.arg("--extern").arg(arg.as_slice());
+                p = p.arg("--extern").arg(arg);
             }
         }
 
@@ -99,5 +99,5 @@ pub fn run_benches(manifest_path: &Path,
     let mut args = args.to_vec();
     args.push("--bench".to_string());
 
-    run_tests(manifest_path, options, args.as_slice())
+    run_tests(manifest_path, options, &args)
 }
index 30e4fb35c882e788e77c3bfb84998ba03aea4528..58ef90a493b33c6f5a2470d456fcf0ac6e29e127 100644 (file)
@@ -24,7 +24,7 @@ pub fn load_lockfile(path: &Path, sid: &SourceId) -> CargoResult<Option<Resolve>
 
     let s = try!(f.read_to_string());
 
-    let table = toml::Value::Table(try!(cargo_toml::parse(s.as_slice(), path)));
+    let table = toml::Value::Table(try!(cargo_toml::parse(&s, path)));
     let mut d = toml::Decoder::new(table);
     let v: resolver::EncodableResolve = try!(Decodable::decode(&mut d));
     Ok(Some(try!(v.to_resolve(sid))))
@@ -60,31 +60,31 @@ pub fn write_lockfile(dst: &Path, resolve: &Resolve) -> CargoResult<()> {
     match e.toml.get(&"metadata".to_string()) {
         Some(metadata) => {
             out.push_str("[metadata]\n");
-            out.push_str(metadata.to_string().as_slice());
+            out.push_str(&metadata.to_string());
         }
         None => {}
     }
 
-    try!(File::create(dst).write_str(out.as_slice()));
+    try!(File::create(dst).write_str(&out));
     Ok(())
 }
 
 fn emit_package(dep: &toml::Table, out: &mut String) {
-    out.push_str(format!("name = {}\n", lookup(dep, "name")).as_slice());
-    out.push_str(format!("version = {}\n", lookup(dep, "version")).as_slice());
+    out.push_str(&format!("name = {}\n", lookup(dep, "name")));
+    out.push_str(&format!("version = {}\n", lookup(dep, "version")));
 
-    if dep.contains_key(&"source".to_string()) {
-        out.push_str(format!("source = {}\n", lookup(dep, "source")).as_slice());
+    if dep.contains_key("source") {
+        out.push_str(&format!("source = {}\n", lookup(dep, "source")));
     }
 
-    if let Some(ref s) = dep.get(&"dependencies".to_string()) {
+    if let Some(ref s) = dep.get("dependencies") {
         let slice = Value::as_slice(*s).unwrap();
 
         if !slice.is_empty() {
             out.push_str("dependencies = [\n");
 
             for child in slice.iter() {
-                out.push_str(format!(" {},\n", child).as_slice());
+                out.push_str(&format!(" {},\n", child));
             }
 
             out.push_str("]\n");
@@ -94,5 +94,5 @@ fn emit_package(dep: &toml::Table, out: &mut String) {
 }
 
 fn lookup<'a>(table: &'a toml::Table, key: &str) -> &'a toml::Value {
-    table.get(&key.to_string()).expect(format!("Didn't find {}", key).as_slice())
+    table.get(key).expect(&format!("didn't find {}", key))
 }
index a338eaabf3ee41d1ac7f7440c217cfeb68385860..ab273b9d740d082d244f68acac99fe2331a7d0bd 100644 (file)
@@ -95,7 +95,7 @@ fn transmit(pkg: &Package, tarball: &Path, registry: &mut Registry)
     } = *manifest.get_metadata();
     let readme = match *readme {
         Some(ref readme) => {
-            let path = pkg.get_root().join(readme.as_slice());
+            let path = pkg.get_root().join(readme);
             Some(try!(File::open(&path).read_to_string().chain_error(|| {
                 human("failed to read the specified README")
             })))
@@ -146,7 +146,7 @@ pub fn registry(config: &Config,
     } = try!(registry_configuration(config));
     let token = token.or(token_config);
     let index = index.or(index_config).unwrap_or(RegistrySource::default_url());
-    let index = try!(index.as_slice().to_url().map_err(human));
+    let index = try!(index.to_url().map_err(human));
     let sid = SourceId::for_registry(&index);
     let api_host = {
         let mut src = RegistrySource::new(&sid, config);
@@ -248,7 +248,7 @@ pub fn modify_owners(config: &Config, opts: &OwnersOptions) -> CargoResult<()> {
             let v = v.iter().map(|s| s.as_slice()).collect::<Vec<_>>();
             try!(config.shell().status("Owner", format!("adding `{:#?}` to `{}`",
                                                         v, name)));
-            try!(registry.add_owners(name.as_slice(), v.as_slice()).map_err(|e| {
+            try!(registry.add_owners(&name, &v).map_err(|e| {
                 human(format!("failed to add owners: {}", e))
             }));
         }
@@ -260,7 +260,7 @@ pub fn modify_owners(config: &Config, opts: &OwnersOptions) -> CargoResult<()> {
             let v = v.iter().map(|s| s.as_slice()).collect::<Vec<_>>();
             try!(config.shell().status("Owner", format!("removing `{:?}` from `{}`",
                                                         v, name)));
-            try!(registry.remove_owners(name.as_slice(), v.as_slice()).map_err(|e| {
+            try!(registry.remove_owners(&name, &v).map_err(|e| {
                 human(format!("failed to add owners: {}", e))
             }));
         }
@@ -268,7 +268,7 @@ pub fn modify_owners(config: &Config, opts: &OwnersOptions) -> CargoResult<()> {
     }
 
     if opts.list {
-        let owners = try!(registry.list_owners(name.as_slice()).map_err(|e| {
+        let owners = try!(registry.list_owners(&name).map_err(|e| {
             human(format!("failed to list owners: {}", e))
         }));
         for owner in owners.iter() {
@@ -311,12 +311,12 @@ pub fn yank(config: &Config,
 
     if undo {
         try!(config.shell().status("Unyank", format!("{}:{}", name, version)));
-        try!(registry.unyank(name.as_slice(), version.as_slice()).map_err(|e| {
+        try!(registry.unyank(&name, &version).map_err(|e| {
             human(format!("failed to undo a yank: {}", e))
         }));
     } else {
         try!(config.shell().status("Yank", format!("{}:{}", name, version)));
-        try!(registry.yank(name.as_slice(), version.as_slice()).map_err(|e| {
+        try!(registry.yank(&name, &version).map_err(|e| {
             human(format!("failed to yank: {}", e))
         }));
     }
@@ -342,7 +342,7 @@ pub fn search(query: &str, config: &Config, index: Option<String>) -> CargoResul
         .map(|krate| (
             format!("{} ({})", krate.name, krate.max_version),
             krate.description.as_ref().map(|desc|
-                truncate_with_ellipsis(desc.replace("\n", " ").as_slice(), 128))
+                truncate_with_ellipsis(&desc.replace("\n", " "), 128))
         ))
         .collect::<Vec<_>>();
     let description_margin = list_items.iter()
@@ -355,7 +355,7 @@ pub fn search(query: &str, config: &Config, index: Option<String>) -> CargoResul
             Some(desc) => {
                 let space = repeat(' ').take(description_margin - name.len())
                                        .collect::<String>();
-                name.to_string() + space.as_slice() + desc.as_slice()
+                name.to_string() + &space + &desc
             }
             None => name
         };
index 24470e59113b71938551e3c369c8e567db6f8eb0..3b5fd1b57ca6a38be1e1e4807fece4d46c3a67ec 100644 (file)
@@ -36,8 +36,7 @@ impl<'a, 'b> GitSource<'a, 'b> {
         let remote = GitRemote::new(source_id.get_url());
         let ident = ident(source_id.get_url());
 
-        let db_path = config.git_db_path()
-            .join(ident.as_slice());
+        let db_path = config.git_db_path().join(&ident);
 
         let reference_path = match *reference {
             GitReference::Branch(ref s) |
@@ -80,7 +79,7 @@ fn ident(url: &Url) -> String {
     let ident = url.path().unwrap_or(&[])
                    .last().map(|a| a.clone()).unwrap_or(String::new());
 
-    let ident = if ident.as_slice() == "" {
+    let ident = if ident == "" {
         "_empty".to_string()
     } else {
         ident
@@ -117,7 +116,7 @@ pub fn canonicalize_url(url: &Url) -> Url {
                 rel.default_port = Some(443);
                 let path = mem::replace(&mut rel.path, Vec::new());
                 rel.path = path.into_iter().map(|s| {
-                    s.as_slice().chars().map(|c| c.to_lowercase()).collect()
+                    s.chars().map(|c| c.to_lowercase()).collect()
                 }).collect();
             }
             _ => {}
@@ -133,7 +132,6 @@ pub fn canonicalize_url(url: &Url) -> Url {
             };
             if needs_chopping {
                 let last = rel.path.pop().unwrap();
-                let last = last.as_slice();
                 rel.path.push(last[..last.len() - 4].to_string())
             }
         }
@@ -217,13 +215,13 @@ mod test {
     #[test]
     pub fn test_url_to_path_ident_with_path() {
         let ident = ident(&url("https://github.com/carlhuda/cargo"));
-        assert_eq!(ident.as_slice(), "cargo-51d6ede913e3e1d5");
+        assert_eq!(ident, "cargo-51d6ede913e3e1d5");
     }
 
     #[test]
     pub fn test_url_to_path_ident_without_path() {
         let ident = ident(&url("https://github.com"));
-        assert_eq!(ident.as_slice(), "_empty-eba8a1ec0f6907fb");
+        assert_eq!(ident, "_empty-eba8a1ec0f6907fb");
     }
 
     #[test]
index 86ab4630cb3959bbe14a520fe2630a1d8bb5b6da..387a1028c3faefddcfbf8af8ad1f8b916df1e015 100644 (file)
@@ -139,7 +139,7 @@ impl GitRemote {
         // Create a local anonymous remote in the repository to fetch the url
         let url = self.url.to_string();
         let refspec = "refs/heads/*:refs/heads/*";
-        fetch(dst, url.as_slice(), refspec)
+        fetch(dst, &url, refspec)
     }
 
     fn clone_into(&self, dst: &Path) -> CargoResult<git2::Repository> {
@@ -149,7 +149,7 @@ impl GitRemote {
         }
         try!(mkdir_recursive(dst, USER_DIR));
         let repo = try!(git2::Repository::init_bare(dst));
-        try!(fetch(&repo, url.as_slice(), "refs/heads/*:refs/heads/*"));
+        try!(fetch(&repo, &url, "refs/heads/*:refs/heads/*"));
         Ok(repo)
     }
 }
@@ -184,7 +184,7 @@ impl GitDatabase {
             GitReference::Tag(ref s) => {
                 try!((|:| {
                     let refname = format!("refs/tags/{}", s);
-                    let id = try!(self.repo.refname_to_id(refname.as_slice()));
+                    let id = try!(self.repo.refname_to_id(&refname));
                     let obj = try!(self.repo.find_object(id, None));
                     let obj = try!(obj.peel(ObjectType::Commit));
                     Ok(obj.id())
@@ -194,8 +194,7 @@ impl GitDatabase {
             }
             GitReference::Branch(ref s) => {
                 try!((|:| {
-                    let b = try!(self.repo.find_branch(s.as_slice(),
-                                                       git2::BranchType::Local));
+                    let b = try!(self.repo.find_branch(s, git2::BranchType::Local));
                     b.get().target().chain_error(|| {
                         human(format!("branch `{}` did not have a target", s))
                     })
@@ -204,15 +203,15 @@ impl GitDatabase {
                 }))
             }
             GitReference::Rev(ref s) => {
-                let obj = try!(self.repo.revparse_single(s.as_slice()));
+                let obj = try!(self.repo.revparse_single(s));
                 obj.id()
             }
         };
         Ok(GitRevision(id))
     }
 
-    pub fn has_ref<S: Str>(&self, reference: S) -> CargoResult<()> {
-        try!(self.repo.revparse_single(reference.as_slice()));
+    pub fn has_ref(&self, reference: &str) -> CargoResult<()> {
+        try!(self.repo.revparse_single(reference));
         Ok(())
     }
 }
@@ -255,8 +254,7 @@ impl<'a> GitCheckout<'a> {
 
         let url = try!(source.to_url().map_err(human));
         let url = url.to_string();
-        let repo = try!(git2::Repository::clone(url.as_slice(),
-                                                into).chain_error(|| {
+        let repo = try!(git2::Repository::clone(&url, into).chain_error(|| {
             internal(format!("failed to clone {} into {}", source.display(),
                              into.display()))
         }));
@@ -275,7 +273,7 @@ impl<'a> GitCheckout<'a> {
         let url = try!(self.database.path.to_url().map_err(human));
         let url = url.to_string();
         let refspec = "refs/heads/*:refs/heads/*";
-        try!(fetch(&self.repo, url.as_slice(), refspec));
+        try!(fetch(&self.repo, &url, refspec));
         Ok(())
     }
 
@@ -370,7 +368,7 @@ fn with_authentication<T, F>(url: &str, cfg: &git2::Config, mut f: F)
             let user = username.map(|s| s.to_string())
                                .or_else(|| cred_helper.username.clone())
                                .unwrap_or("git".to_string());
-            git2::Cred::ssh_key_from_agent(user.as_slice())
+            git2::Cred::ssh_key_from_agent(&user)
         } else if allowed.contains(git2::USER_PASS_PLAINTEXT) {
             git2::Cred::credential_helper(cfg, url, username)
         } else if allowed.contains(git2::DEFAULT) {
@@ -397,8 +395,7 @@ pub fn fetch(repo: &git2::Repository, url: &str,
     with_authentication(url, &try!(repo.config()), |f| {
         let mut cb = git2::RemoteCallbacks::new();
         cb.credentials(|a, b, c| f(a, b, c));
-        let mut remote = try!(repo.remote_anonymous(url.as_slice(),
-                                                    Some(refspec)));
+        let mut remote = try!(repo.remote_anonymous(&url, Some(refspec)));
         try!(remote.add_fetch("refs/tags/*:refs/tags/*"));
         remote.set_callbacks(&mut cb);
         try!(remote.fetch(&["refs/tags/*:refs/tags/*", refspec], None, None));
index a8ef8b5c920802298e56753f7705b46e7f5666ac..6d825a36975df8c89118651c5ced7993f3352023 100644 (file)
@@ -75,7 +75,7 @@ impl<'a, 'b> PathSource<'a, 'b> {
         let root = pkg.get_manifest_path().dir_path();
 
         let parse = |&: p: &String| {
-            Pattern::new(p.as_slice()).map_err(|e| {
+            Pattern::new(p).map_err(|e| {
                 human(format!("could not parse pattern `{}`: {}", p, e))
             })
         };
@@ -127,7 +127,7 @@ impl<'a, 'b> PathSource<'a, 'b> {
 
         let mut ret = Vec::new();
         'outer: for entry in index.iter() {
-            let fname = entry.path.as_slice();
+            let fname = &entry.path[];
             let file_path = root.join(fname);
 
             // Filter out files outside this package.
index 28beb5f462cee4b71188fe69a90dceb649a783cb..b31e0ae23b1a0250c6244654505b54cd92a80035 100644 (file)
@@ -232,9 +232,9 @@ impl<'a, 'b> RegistrySource<'a, 'b> {
         let ident = source_id.get_url().host().unwrap().to_string();
         let part = format!("{}-{}", ident, hash);
         RegistrySource {
-            checkout_path: config.registry_index_path().join(part.as_slice()),
-            cache_path: config.registry_cache_path().join(part.as_slice()),
-            src_path: config.registry_source_path().join(part.as_slice()),
+            checkout_path: config.registry_index_path().join(&part),
+            cache_path: config.registry_cache_path().join(&part),
+            src_path: config.registry_source_path().join(&part),
             config: config,
             source_id: source_id.clone(),
             handle: None,
@@ -252,7 +252,7 @@ impl<'a, 'b> RegistrySource<'a, 'b> {
     pub fn url(config: &Config) -> CargoResult<Url> {
         let config = try!(ops::registry_configuration(config));
         let url = config.index.unwrap_or(DEFAULT.to_string());
-        url.as_slice().to_url().map_err(human)
+        url.to_url().map_err(human)
     }
 
     /// Get the default url for the registry
@@ -266,7 +266,7 @@ impl<'a, 'b> RegistrySource<'a, 'b> {
     pub fn config(&self) -> CargoResult<RegistryConfig> {
         let mut f = try!(File::open(&self.checkout_path.join("config.json")));
         let contents = try!(f.read_to_string());
-        let config = try!(json::decode(contents.as_slice()));
+        let config = try!(json::decode(&contents));
         Ok(config)
     }
 
@@ -328,7 +328,7 @@ impl<'a, 'b> RegistrySource<'a, 'b> {
             state.update(resp.get_body());
             state.finish()
         };
-        if actual.as_slice().to_hex() != *expected {
+        if actual.to_hex() != *expected {
             return Err(human(format!("Failed to verify the checksum of `{}`",
                                      pkg)))
         }
@@ -376,7 +376,7 @@ impl<'a, 'b> RegistrySource<'a, 'b> {
             Ok(mut f) => {
                 let contents = try!(f.read_to_string());
                 let ret: CargoResult<Vec<(Summary, bool)>>;
-                ret = contents.as_slice().lines().filter(|l| l.trim().len() > 0)
+                ret = contents.lines().filter(|l| l.trim().len() > 0)
                               .map(|l| self.parse_registry_package(l))
                               .collect();
                 try!(ret.chain_error(|| {
@@ -402,9 +402,7 @@ impl<'a, 'b> RegistrySource<'a, 'b> {
         let RegistryPackage {
             name, vers, cksum, deps, features, yanked
         } = try!(json::decode::<RegistryPackage>(line));
-        let pkgid = try!(PackageId::new(name.as_slice(),
-                                        vers.as_slice(),
-                                        &self.source_id));
+        let pkgid = try!(PackageId::new(&name, &vers, &self.source_id));
         let deps: CargoResult<Vec<Dependency>> = deps.into_iter().map(|dep| {
             self.parse_registry_dependency(dep)
         }).collect();
@@ -420,7 +418,7 @@ impl<'a, 'b> RegistrySource<'a, 'b> {
             name, req, features, optional, default_features, target, kind
         } = dep;
 
-        let dep = try!(Dependency::parse(name.as_slice(), Some(req.as_slice()),
+        let dep = try!(Dependency::parse(&name, Some(&req),
                                          &self.source_id));
         let kind = match kind.as_ref().map(|s| s.as_slice()).unwrap_or("") {
             "dev" => Kind::Development,
@@ -446,7 +444,7 @@ impl<'a, 'b> RegistrySource<'a, 'b> {
         // git fetch origin
         let url = self.source_id.get_url().to_string();
         let refspec = "refs/heads/*:refs/remotes/origin/*";
-        try!(git::fetch(&repo, url.as_slice(), refspec).chain_error(|| {
+        try!(git::fetch(&repo, &url, refspec).chain_error(|| {
             internal(format!("failed to fetch `{}`", url))
         }));
 
@@ -518,7 +516,7 @@ impl<'a, 'b> Source for RegistrySource<'a, 'b> {
 
     fn download(&mut self, packages: &[PackageId]) -> CargoResult<()> {
         let config = try!(self.config());
-        let url = try!(config.dl.as_slice().to_url().map_err(internal));
+        let url = try!(config.dl.to_url().map_err(internal));
         for package in packages.iter() {
             if self.source_id != *package.get_source_id() { continue }
 
index dba02d56517630d2945eac49c6a6272b87ee85f4..217d02811104f709689b581f5d66e2764d2a2bb0 100644 (file)
@@ -76,14 +76,10 @@ impl<'a> Config<'a> {
     }
 
     /// Return the output of `rustc -v verbose`
-    pub fn rustc_version(&self) -> &str {
-        self.rustc_version.as_slice()
-    }
+    pub fn rustc_version(&self) -> &str { &self.rustc_version }
 
     /// Return the host platform and default target of rustc
-    pub fn rustc_host(&self) -> &str {
-        self.rustc_host.as_slice()
-    }
+    pub fn rustc_host(&self) -> &str { &self.rustc_host }
 
     pub fn values(&self) -> CargoResult<Ref<HashMap<String, ConfigValue>>> {
         if !self.values_loaded.get() {
@@ -164,8 +160,7 @@ impl<'a> Config<'a> {
         try!(walk_tree(&self.cwd, |mut file| {
             let path = file.path().clone();
             let contents = try!(file.read_to_string());
-            let table = try!(cargo_toml::parse(contents.as_slice(),
-                                               &path).chain_error(|| {
+            let table = try!(cargo_toml::parse(&contents, &path).chain_error(|| {
                 human(format!("could not parse TOML configuration in `{}`",
                               path.display()))
             }));
@@ -316,7 +311,7 @@ impl ConfigValue {
 
     pub fn string(&self) -> CargoResult<(&str, &Path)> {
         match *self {
-            CV::String(ref s, ref p) => Ok((s.as_slice(), p)),
+            CV::String(ref s, ref p) => Ok((s, p)),
             _ => self.expected("string"),
         }
     }
@@ -330,7 +325,7 @@ impl ConfigValue {
 
     pub fn list(&self) -> CargoResult<&[(String, Path)]> {
         match *self {
-            CV::List(ref list, _) => Ok(list.as_slice()),
+            CV::List(ref list, _) => Ok(list),
             _ => self.expected("list"),
         }
     }
@@ -436,8 +431,9 @@ pub fn set_config(cfg: &Config, loc: Location, key: &str,
     };
     try!(fs::mkdir_recursive(&file.dir_path(), old_io::USER_DIR));
     let contents = File::open(&file).read_to_string().unwrap_or("".to_string());
-    let mut toml = try!(cargo_toml::parse(contents.as_slice(), &file));
+    let mut toml = try!(cargo_toml::parse(&contents, &file));
     toml.insert(key.to_string(), value.into_toml());
-    try!(File::create(&file).write_all(toml::Value::Table(toml).to_string().as_bytes()));
+    let mut out = try!(File::create(&file));
+    try!(out.write_all(toml::Value::Table(toml).to_string().as_bytes()));
     Ok(())
 }
index ff5c0add9ed3e7ad0bfeb7987a3ef2b1e7d02486..5b03a9668f7d403c37e234dfaab90a23603a9a49 100644 (file)
@@ -106,7 +106,7 @@ pub struct ProcessError {
 }
 
 impl Error for ProcessError {
-    fn description(&self) -> &str { self.desc.as_slice() }
+    fn description(&self) -> &str { &self.desc }
     fn cause(&self) -> Option<&Error> {
         self.cause.as_ref().map(|s| s as &Error)
     }
@@ -149,7 +149,7 @@ impl fmt::Debug for ConcreteCargoError {
 }
 
 impl Error for ConcreteCargoError {
-    fn description(&self) -> &str { self.description.as_slice() }
+    fn description(&self) -> &str { &self.description }
     fn cause(&self) -> Option<&Error> {
         self.cause.as_ref().map(|c| {
             let e: &Error = &**c; e
@@ -208,8 +208,8 @@ impl fmt::Display for CliError {
 }
 
 impl CliError {
-    pub fn new<S: Str>(error: S, code: i32) -> CliError {
-        let error = human(error.as_slice().to_string());
+    pub fn new(error: &str, code: i32) -> CliError {
+        let error = human(error.to_string());
         CliError::from_boxed(error, code)
     }
 
@@ -273,25 +273,25 @@ impl CargoError for str::Utf8Error {}
 // =============================================================================
 // Construction helpers
 
-pub fn process_error<S: Str>(msg: S,
-                             cause: Option<IoError>,
-                             status: Option<&ProcessExit>,
-                             output: Option<&ProcessOutput>) -> ProcessError {
+pub fn process_error(msg: &str,
+                     cause: Option<IoError>,
+                     status: Option<&ProcessExit>,
+                     output: Option<&ProcessOutput>) -> ProcessError {
     let exit = match status {
         Some(&ExitStatus(i)) | Some(&ExitSignal(i)) => i.to_string(),
         None => "never executed".to_string(),
     };
-    let mut desc = format!("{} (status={})", msg.as_slice(), exit);
+    let mut desc = format!("{} (status={})", &msg, exit);
 
     if let Some(out) = output {
-        match str::from_utf8(out.output.as_slice()) {
+        match str::from_utf8(&out.output) {
             Ok(s) if s.trim().len() > 0 => {
                 desc.push_str("\n--- stdout\n");
                 desc.push_str(s);
             }
             Ok(..) | Err(..) => {}
         }
-        match str::from_utf8(out.error.as_slice()) {
+        match str::from_utf8(&out.error) {
             Ok(s) if s.trim().len() > 0 => {
                 desc.push_str("\n--- stderr\n");
                 desc.push_str(s);
@@ -308,11 +308,10 @@ pub fn process_error<S: Str>(msg: S,
     }
 }
 
-pub fn internal_error<S1: Str, S2: Str>(error: S1,
-                                        detail: S2) -> Box<CargoError> {
+pub fn internal_error(error: &str, detail: &str) -> Box<CargoError> {
     Box::new(ConcreteCargoError {
-        description: error.as_slice().to_string(),
-        detail: Some(detail.as_slice().to_string()),
+        description: error.to_string(),
+        detail: Some(detail.to_string()),
         cause: None,
         is_human: false
     })
index a29b3b9025fd8500e8cdf9357379c70f11644b04..290b65aab4896f4176dd8b18a0f31fd89957f1c9 100644 (file)
@@ -41,7 +41,7 @@ impl ProcessBuilder {
     }
 
     pub fn get_args(&self) -> &[CString] {
-        self.args.as_slice()
+        &self.args
     }
 
     pub fn cwd(mut self, path: Path) -> ProcessBuilder {
@@ -64,16 +64,16 @@ impl ProcessBuilder {
                .stdin(InheritFd(0));
 
         let exit = try!(command.status().map_err(|e| {
-            process_error(format!("Could not execute process `{}`",
-                                  self.debug_string()),
+            process_error(&format!("Could not execute process `{}`",
+                                   self.debug_string()),
                           Some(e), None, None)
         }));
 
         if exit.success() {
             Ok(())
         } else {
-            Err(process_error(format!("Process didn't exit successfully: `{}`",
-                                      self.debug_string()),
+            Err(process_error(&format!("Process didn't exit successfully: `{}`",
+                                       self.debug_string()),
                               None, Some(&exit), None))
         }
     }
@@ -82,16 +82,16 @@ impl ProcessBuilder {
         let command = self.build_command();
 
         let output = try!(command.output().map_err(|e| {
-            process_error(format!("Could not execute process `{}`",
-                              self.debug_string()),
+            process_error(&format!("Could not execute process `{}`",
+                               self.debug_string()),
                           Some(e), None, None)
         }));
 
         if output.status.success() {
             Ok(output)
         } else {
-            Err(process_error(format!("Process didn't exit successfully: `{}`",
-                                      self.debug_string()),
+            Err(process_error(&format!("Process didn't exit successfully: `{}`",
+                                       self.debug_string()),
                               None, Some(&output.status), Some(&output)))
         }
     }
@@ -103,7 +103,6 @@ impl ProcessBuilder {
             command.arg(arg);
         }
         for (k, v) in self.env.iter() {
-            let k = k.as_slice();
             match *v {
                 Some(ref v) => { command.env(k, v); }
                 None => { command.env_remove(k); }
index e17df6d22166ba59d381641e81e4405aab55e504..9d19c36dd8122f7126af08281fc974d8cf4cfb9d 100644 (file)
@@ -39,8 +39,9 @@ impl Drop for Profiler {
                 let mut last = 0;
                 for (i, &(l, time, ref msg)) in msgs.iter().enumerate() {
                     if l != lvl { continue }
-                    println!("{} {:6}ms - {}", repeat("    ").take(lvl + 1).collect::<String>(),
-                        time / 1000000, msg);
+                    println!("{} {:6}ms - {}",
+                             repeat("    ").take(lvl + 1).collect::<String>(),
+                             time / 1000000, msg);
 
                     print(lvl + 1, &msgs[last..i]);
                     last = i;
@@ -49,8 +50,9 @@ impl Drop for Profiler {
             }
             MESSAGES.with(|msgs_rc| {
                 let mut msgs = msgs_rc.borrow_mut();
-                msgs.push((0, end - start, mem::replace(&mut self.desc, String::new())));
-                print(0, msgs.as_slice());
+                msgs.push((0, end - start,
+                           mem::replace(&mut self.desc, String::new())));
+                print(0, &msgs);
             });
         } else {
             MESSAGES.with(|msgs| {
index 9ea92161d0eca362f4d673dc220b12ce91e6e0d9..9fe689b133de3993879b1c089d97779675239774 100644 (file)
@@ -16,3 +16,9 @@ impl<'a> ToSemver for &'a str {
         }
     }
 }
+
+impl<'a> ToSemver for &'a String {
+    fn to_semver(self) -> Result<Version, String> {
+        (**self).to_semver()
+    }
+}
index cab0a356abdf4f70e2ca486fce926f2f78a61de5..d774a6a69fab9b38f919c2d2fcdf3da937163995 100644 (file)
@@ -128,7 +128,7 @@ pub fn to_manifest(contents: &[u8],
                     add_unused_keys(m, v, if key.len() == 0 {
                         k.clone()
                     } else {
-                        key.clone() + "." + k.as_slice()
+                        key.clone() + "." + k
                     })
                 }
             }
@@ -143,7 +143,7 @@ pub fn to_manifest(contents: &[u8],
 }
 
 pub fn parse(toml: &str, file: &Path) -> CargoResult<toml::Table> {
-    let mut parser = toml::Parser::new(toml.as_slice());
+    let mut parser = toml::Parser::new(&toml);
     match parser.parse() {
         Some(toml) => return Ok(toml),
         None => {}
@@ -152,16 +152,16 @@ pub fn parse(toml: &str, file: &Path) -> CargoResult<toml::Table> {
     for error in parser.errors.iter() {
         let (loline, locol) = parser.to_linecol(error.lo);
         let (hiline, hicol) = parser.to_linecol(error.hi);
-        error_str.push_str(format!("{}:{}:{}{} {}\n",
-                                   file.display(),
-                                   loline + 1, locol + 1,
-                                   if loline != hiline || locol != hicol {
-                                       format!("-{}:{}", hiline + 1,
-                                               hicol + 1)
-                                   } else {
-                                       "".to_string()
-                                   },
-                                   error.desc).as_slice());
+        error_str.push_str(&format!("{}:{}:{}{} {}\n",
+                                    file.display(),
+                                    loline + 1, locol + 1,
+                                    if loline != hiline || locol != hicol {
+                                        format!("-{}:{}", hiline + 1,
+                                                hicol + 1)
+                                    } else {
+                                        "".to_string()
+                                    },
+                                    error.desc));
     }
     Err(human(error_str))
 }
@@ -241,7 +241,7 @@ pub enum ManyOrOne<T> {
 impl<T> ManyOrOne<T> {
     fn as_slice(&self) -> &[T] {
         match *self {
-            ManyOrOne::Many(ref v) => v.as_slice(),
+            ManyOrOne::Many(ref v) => v,
             ManyOrOne::One(ref t) => slice::ref_slice(t),
         }
     }
@@ -275,16 +275,16 @@ pub struct TomlVersion {
 impl Decodable for TomlVersion {
     fn decode<D: Decoder>(d: &mut D) -> Result<TomlVersion, D::Error> {
         let s = try!(d.read_str());
-        match s.as_slice().to_semver() {
+        match s.to_semver() {
             Ok(s) => Ok(TomlVersion { version: s }),
-            Err(e) => Err(d.error(e.as_slice())),
+            Err(e) => Err(d.error(&e)),
         }
     }
 }
 
 impl TomlProject {
     pub fn to_package_id(&self, source_id: &SourceId) -> CargoResult<PackageId> {
-        PackageId::new(self.name.as_slice(), self.version.version.clone(),
+        PackageId::new(&self.name, self.version.version.clone(),
                        source_id)
     }
 }
@@ -403,7 +403,7 @@ impl TomlManifest {
                     }
                 }).collect()
             }
-            None => inferred_lib_target(project.name.as_slice(), layout),
+            None => inferred_lib_target(&project.name, layout),
         };
 
         let bins = match self.bin {
@@ -421,7 +421,7 @@ impl TomlManifest {
                     }
                 }).collect()
             }
-            None => inferred_bin_targets(project.name.as_slice(), layout)
+            None => inferred_bin_targets(&project.name, layout)
         };
 
         let examples = match self.example {
@@ -445,12 +445,12 @@ impl TomlManifest {
 
         // Get targets
         let profiles = self.profile.clone().unwrap_or(Default::default());
-        let targets = normalize(lib.as_slice(),
-                                bins.as_slice(),
+        let targets = normalize(&lib,
+                                &bins,
                                 new_build,
-                                examples.as_slice(),
-                                tests.as_slice(),
-                                benches.as_slice(),
+                                &examples,
+                                &tests,
+                                &benches,
                                 &metadata,
                                 &profiles);
 
@@ -551,20 +551,20 @@ fn process_dependencies<F>(cx: &mut Context,
 
         let new_source_id = match details.git {
             Some(ref git) => {
-                let loc = try!(git.as_slice().to_url().map_err(|e| {
+                let loc = try!(git.to_url().map_err(|e| {
                     human(e)
                 }));
                 Some(SourceId::for_git(&loc, reference))
             }
             None => {
                 details.path.as_ref().map(|path| {
-                    cx.nested_paths.push(Path::new(path.as_slice()));
+                    cx.nested_paths.push(Path::new(path));
                     cx.source_id.clone()
                 })
             }
         }.unwrap_or(try!(SourceId::for_central(cx.config)));
 
-        let dep = try!(Dependency::parse(n.as_slice(),
+        let dep = try!(Dependency::parse(&n,
                                          details.version.as_ref()
                                                 .map(|v| v.as_slice()),
                                          &new_source_id));
@@ -622,7 +622,7 @@ impl TomlTarget {
 impl PathValue {
     fn to_path(&self) -> Path {
         match *self {
-            PathValue::String(ref s) => Path::new(s.as_slice()),
+            PathValue::String(ref s) => Path::new(s),
             PathValue::Path(ref p) => p.clone(),
         }
     }
@@ -718,7 +718,8 @@ fn normalize(libs: &[TomlLibTarget],
             PathValue::String(format!("src/{}.rs", l.name))
         });
         let crate_types = l.crate_type.clone().and_then(|kinds| {
-            LibKind::from_strs(kinds).ok()
+            kinds.iter().map(|s| LibKind::from_str(s))
+                 .collect::<CargoResult<_>>().ok()
         }).unwrap_or_else(|| {
             vec![if l.plugin == Some(true) {LibKind::Dylib} else {LibKind::Lib}]
         });
@@ -730,7 +731,7 @@ fn normalize(libs: &[TomlLibTarget],
             if profile.is_test() {
                 metadata.mix(&"test");
             }
-            dst.push(Target::lib_target(l.name.as_slice(), crate_types.clone(),
+            dst.push(Target::lib_target(&l.name, crate_types.clone(),
                                         &path.to_path(), profile,
                                         metadata));
         }
@@ -758,7 +759,7 @@ fn normalize(libs: &[TomlLibTarget],
                 } else {
                     None
                 };
-                dst.push(Target::bin_target(bin.name.as_slice(),
+                dst.push(Target::bin_target(&bin.name,
                                             &path.to_path(),
                                             profile,
                                             metadata));
@@ -776,8 +777,7 @@ fn normalize(libs: &[TomlLibTarget],
         let name = format!("build-script-{}", cmd.filestem_str().unwrap_or(""));
 
         for profile in profiles.iter() {
-            dst.push(Target::custom_build_target(name.as_slice(),
-                                                 cmd, profile, None));
+            dst.push(Target::custom_build_target(&name, cmd, profile, None));
         }
     }
 
@@ -791,10 +791,10 @@ fn normalize(libs: &[TomlLibTarget],
 
             let profile = merge(Profile::default_example(), &profiles.test);
             let profile_release = merge(Profile::default_release(), &profiles.release);
-            dst.push(Target::example_target(ex.name.as_slice(),
+            dst.push(Target::example_target(&ex.name,
                                             &path.to_path(),
                                             &profile));
-            dst.push(Target::example_target(ex.name.as_slice(),
+            dst.push(Target::example_target(&ex.name,
                                             &path.to_path(),
                                             &profile_release));
         }
@@ -817,7 +817,7 @@ fn normalize(libs: &[TomlLibTarget],
 
             let profile = Profile::default_test().harness(harness);
             let profile = merge(profile, &profiles.test);
-            dst.push(Target::test_target(test.name.as_slice(),
+            dst.push(Target::test_target(&test.name,
                                          &path.to_path(),
                                          &profile,
                                          metadata));
@@ -841,7 +841,7 @@ fn normalize(libs: &[TomlLibTarget],
 
             let profile = Profile::default_bench().harness(harness);
             let profile = merge(profile, &profiles.bench);
-            dst.push(Target::bench_target(bench.name.as_slice(),
+            dst.push(Target::bench_target(&bench.name,
                                           &path.to_path(),
                                           &profile,
                                           metadata));
@@ -881,7 +881,7 @@ fn normalize(libs: &[TomlLibTarget],
 
     test_targets(&mut ret, tests, metadata, profiles,
                 |test| {
-                    if test.name.as_slice() == "test" {
+                    if test.name == "test" {
                         "src/test.rs".to_string()
                     } else {
                         format!("tests/{}.rs", test.name)
@@ -889,7 +889,7 @@ fn normalize(libs: &[TomlLibTarget],
 
     bench_targets(&mut ret, benches, metadata, profiles,
                  |bench| {
-                     if bench.name.as_slice() == "bench" {
+                     if bench.name == "bench" {
                          "src/bench.rs".to_string()
                      } else {
                          format!("benches/{}.rs", bench.name)
index 5ea5c0cee1a5c6c512c4394eeaa66612a8e6c30b..887264fc535a21055b23340932d2e3c2844b4621 100644 (file)
@@ -108,7 +108,7 @@ impl Registry {
         let body = json::encode(&OwnersReq { users: owners }).unwrap();
         let body = try!(self.put(format!("/crates/{}/owners", krate),
                                  body.as_bytes()));
-        assert!(json::decode::<R>(body.as_slice()).unwrap().ok);
+        assert!(json::decode::<R>(&body).unwrap().ok);
         Ok(())
     }
 
@@ -116,13 +116,13 @@ impl Registry {
         let body = json::encode(&OwnersReq { users: owners }).unwrap();
         let body = try!(self.delete(format!("/crates/{}/owners", krate),
                                     Some(body.as_bytes())));
-        assert!(json::decode::<R>(body.as_slice()).unwrap().ok);
+        assert!(json::decode::<R>(&body).unwrap().ok);
         Ok(())
     }
 
     pub fn list_owners(&mut self, krate: &str) -> Result<Vec<User>> {
         let body = try!(self.get(format!("/crates/{}/owners", krate)));
-        Ok(json::decode::<Users>(body.as_slice()).unwrap().users)
+        Ok(json::decode::<Users>(&body).unwrap().users)
     }
 
     pub fn publish(&mut self, krate: &NewCrate, tarball: &Path) -> Result<()> {
@@ -137,7 +137,7 @@ impl Registry {
         let header = {
             let mut w = MemWriter::new();
             w.write_le_u32(json.len() as u32).unwrap();
-            w.write_str(json.as_slice()).unwrap();
+            w.write_str(&json).unwrap();
             w.write_le_u32(stat.size as u32).unwrap();
             MemReader::new(w.into_inner())
         };
@@ -148,33 +148,34 @@ impl Registry {
 
         let url = format!("{}/api/v1/crates/new", self.host);
 
-        let token = try!(self.token.as_ref().ok_or(Error::TokenMissing)).as_slice();
+        let token = try!(self.token.as_ref().ok_or(Error::TokenMissing));
         let request = self.handle.put(url, &mut body)
             .content_length(size)
             .header("Accept", "application/json")
-            .header("Authorization", token);
+            .header("Authorization", &token);
         let response = handle(request.exec());
         let _body = try!(response);
         Ok(())
     }
 
     pub fn search(&mut self, query: &str) -> Result<Vec<Crate>> {
-        let body = try!(self.req(format!("/crates?q={}", query), None, Get, Auth::Unauthorized));
+        let body = try!(self.req(format!("/crates?q={}", query), None, Get,
+                                 Auth::Unauthorized));
 
-        Ok(json::decode::<Crates>(body.as_slice()).unwrap().crates)
+        Ok(json::decode::<Crates>(&body).unwrap().crates)
     }
 
     pub fn yank(&mut self, krate: &str, version: &str) -> Result<()> {
         let body = try!(self.delete(format!("/crates/{}/{}/yank", krate, version),
                                     None));
-        assert!(json::decode::<R>(body.as_slice()).unwrap().ok);
+        assert!(json::decode::<R>(&body).unwrap().ok);
         Ok(())
     }
 
     pub fn unyank(&mut self, krate: &str, version: &str) -> Result<()> {
         let body = try!(self.put(format!("/crates/{}/{}/unyank", krate, version),
                                  &[]));
-        assert!(json::decode::<R>(body.as_slice()).unwrap().ok);
+        assert!(json::decode::<R>(&body).unwrap().ok);
         Ok(())
     }
 
@@ -198,8 +199,8 @@ impl Registry {
                               .content_type("application/json");
 
         if authorized == Auth::Authorized {
-            let token = try!(self.token.as_ref().ok_or(Error::TokenMissing)).as_slice();
-            req = req.header("Authorization", token);
+            let token = try!(self.token.as_ref().ok_or(Error::TokenMissing));
+            req = req.header("Authorization", &token);
         }
         match body {
             Some(b) => req = req.body(b),
@@ -223,7 +224,7 @@ fn handle(response: result::Result<http::Response, curl::ErrCode>)
         Ok(body) => body,
         Err(..) => return Err(Error::NonUtf8Body),
     };
-    match json::decode::<ApiErrorList>(body.as_slice()) {
+    match json::decode::<ApiErrorList>(&body) {
         Ok(errors) => {
             return Err(Error::Api(errors.errors.into_iter().map(|s| s.detail)
                                         .collect()))